home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cgazv5n4.arc / STRINGC.CPP < prev    next >
C/C++ Source or Header  |  1991-09-23  |  2KB  |  84 lines

  1. //--- STRINGC.CPP ------------------------ Listing 2 -----------
  2. // Implementation of string class
  3. // by Bruce Eckel. See Listing 1 for copyright information.
  4. //--------------------------------------------------------------
  5.  
  6. #include "stringc.h"
  7.  
  8. void string::erase_string() {
  9.   cursor = head;
  10.   while(cursor) {
  11.     cursor = cursor->next;
  12.     delete head;
  13.     head = cursor;
  14.   }
  15. }
  16.  
  17. void string::defragment() {
  18.   if(head->next == NULL) return;  // only 1 piece
  19.   cursor = head;
  20.   char* temp = new char[Length + 1];
  21.   int index = 0;
  22.   while(cursor != NULL) {
  23.     strcpy(temp + index, cursor->str);
  24.     index += cursor->plength;
  25.     cursor = cursor->next;
  26.   }
  27.   erase_string();
  28.   cursor = head = new piece(NULL,temp);  // Length stays the same
  29. }
  30.  
  31. string::string(char * s) {
  32.   cursor = head = new piece(NULL, s);
  33.   Length = strlen(s);
  34. }
  35.  
  36. void string::append(char * s) {
  37.   cursor->next = new piece(NULL, s);
  38.   cursor = cursor->next;
  39.   Length += cursor->plength;
  40. }
  41.  
  42. void string::prepend(char* s) {
  43.   head = new piece(head,s);
  44.   Length += head->plength;
  45. }
  46.  
  47. void string::insert(int position, char* s) {
  48.   if(position <= 0) { prepend(s); return; }
  49.   if(position >= Length) { append(s); return; }
  50.   defragment();
  51.   head->break_piece(position);
  52.   cursor = head->next;
  53.   head->next = new piece(head->next, s);  // insert the piece
  54.   Length += head->next->plength;  // ... and adjust the length
  55. }
  56.  
  57. void string::erase(int position, int count) {
  58.   defragment();
  59.   if(position < 0 || position >= Length) return;
  60.   head->break_piece(position);
  61.   cursor = head->next;
  62.   if(count > cursor->plength) count = cursor->plength;
  63.   cursor->break_piece(count);  // break off the end to save
  64.   Length -= head->next->plength // adjust length
  65.   head->next = cursor->next;  // thread past the piece to delete
  66.   delete cursor;
  67.   cursor = head->next;  // put the cursor at the end
  68. }
  69.  
  70. int string::search(char * findstring) {
  71.   defragment();
  72.   char * start = strstr(head->str, findstring);
  73.   if(start == NULL) return -1;  // means string not found
  74.   return start - head->str;  // index of starting position
  75. }
  76.  
  77. void string::print() {
  78.   piece * cur = head;
  79.   while(cur) {
  80.     cur->print();  // calls piece::print() since cur is a piece
  81.     cur = cur->next;
  82.   }
  83.   printf("\n");
  84. }